import { Space, Avatar, Menu, message } from 'antd'
import { FC } from 'react'
import { history, useModel, useSelector } from 'umi'
import styles from './index.less'
import { useDispatch } from 'dva'
import { ACTIONS } from '@/models'
import HeaderDropdown from '../HeaderDropdown'
import userLogo from '@/assets/user.svg'
import userLogo1 from '@/assets/user1.svg'
import { useEffect } from 'react'

const GlobalHeaderRight: FC = () => {
  const user = useSelector((state: any) => state.user)
  const dispatch = useDispatch()
  useEffect(() => {
    if (user?.isLogin || !localStorage.getItem('token')) {
      return
    }
    dispatch({
      type: ACTIONS.user.loginWithToken
    })
  }, [])
  //未登录Menu
  const unLoginMenu = (
    <Menu>
      <Menu.Item key="1">
        <span style={{ color: '#1890ff' }} onClick={() => history.push('/user/login')}>
          登录
        </span>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="2">
        <span style={{ color: '#1890ff' }} onClick={() => history.push('/user/signUP')}>
          注册
        </span>
      </Menu.Item>
    </Menu>
  )
  //登录Menu
  const loginMenu = (
    <Menu>
      <Menu.Item>
        <span style={{ color: '#1890ff' }} onClick={() => message.error('尚未完善！')}>
          个人信息
        </span>
      </Menu.Item>
      <Menu.Item>
        <span
          style={{ color: '#1890ff' }}
          onClick={() => {
            dispatch({
              type: ACTIONS.user.logout
            })
            if (window.location.pathname !== 'user/login') {
              history.replace({
                pathname: 'user/login',
                search: JSON.stringify({
                  redirect: window.location.href
                })
              })
            }
          }}
        >
          退出登录
        </span>
      </Menu.Item>
    </Menu>
  )
  return (
    <HeaderDropdown overlay={user?.isLogin ? loginMenu : unLoginMenu} placement="bottomLeft">
      <Space>
        {' '}
        <span>
          {' '}
          <Avatar src={user?.isLogin ? userLogo1 : userLogo} />
        </span>
        <span style={{ fontWeight: 'bold' }}>
          {/* {user?.isLogin ? user?.userInfo?.username : '未登录'} */}
          {localStorage.getItem('token') ? user?.userInfo?.username : '未登录'}
        </span>
      </Space>
    </HeaderDropdown>
  )
}
export default GlobalHeaderRight
